package com.nulstudio.sppm.Interceptor;
import com.nulstudio.sppm.Annotation.NormalJwt;
import com.nulstudio.sppm.Utils.JwtUtils;
import com.nulstudio.sppm.Utils.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Slf4j
public class LoginJwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) {

        String token = RequestUtils.getCurrentToken(httpServletRequest);

        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();

        if (method.isAnnotationPresent(NormalJwt.class)) {
            NormalJwt normalJwt = method.getAnnotation(NormalJwt.class);
            if (normalJwt.required()) {

                if (token.isEmpty()) {
                    throw new RuntimeException("no token for access");
                }

                String userId = JwtUtils.getUserId(token);
                log.info("用户id: {}", userId);

                JwtUtils.checkSign(token);
            }
        }
        return true;
    }
}
